package com.vcs.frm.web.school.noticeBoard;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.vcs.frm.dao.CommonDao;
import com.vcs.frm.domain.NoticeBoard;
import com.vcs.frm.service.CommonService;
import com.vcs.frm.web.form.school.NewAdmissionForm;


@Controller
@RequestMapping("/school")
public class NoticeBoardController {

	@Autowired
	private CommonService commonService;
	
	public void setCommonService(CommonService commonService) {
		this.commonService = commonService;
	}
	
	@RequestMapping(value="/updateNoticeBoard", method = RequestMethod.GET)
	public ModelAndView updateNoticeBoard(){
		ModelAndView mav = new ModelAndView();
		
		NoticeBoard noticeBoard = commonService.getNoticeBoard();
		
		mav.addObject("noticeBoard", noticeBoard);
		 
		mav.setViewName("updateNoticeBoard");
		return mav;
		
	}
	
	@RequestMapping(value="/updateNoticeBoard", method = RequestMethod.POST)
	public ModelAndView processNoticeBoardForm(@ModelAttribute("noticeBoard") @Valid NoticeBoard noticeBoard,
			BindingResult bindingResult, HttpSession session){
		ModelAndView mav = new ModelAndView();
		System.out.println("*******"+noticeBoard);
		
		// get logged-in user's name
		SecurityContext sContext = (SecurityContext) session.getAttribute("SPRING_SECURITY_CONTEXT");
		if(sContext != null && sContext.getAuthentication() != null)
		{
			User user = (User) sContext.getAuthentication().getPrincipal();
			noticeBoard.setUpdatedBy(StringUtils.capitalize(user.getUsername()));
		}
		noticeBoard.setUpdatedDate(new Date());
		
		commonService.updateNoticeBoards(noticeBoard);
//		List<NoticeBoard> noticeBoard = commonService.getNoticeBoards();
//		NoticeBoard nb = noticeBoard.get(0);
		mav.addObject("noticeBoard", noticeBoard);
		mav.addObject("success", true);
		mav.setViewName("updateNoticeBoard");
		return mav;
	}
	
}
